<?php

namespace app\admin\controller;

use app\common\controller\publics\Jwt;
use think\Controller;
use think\Db;
use think\facade\Cache;
use think\Request;
use Zewail\Api\JWT\Factories\Code;

class Content extends Controller
{
    public function initialize()
    {
        error_reporting(5);//1+4
        //设置跨域头
        header('Access-Control-Allow-Origin: *');
        //token 验证登录信息是否有效
        $request = new Request();
        $g=$request->get();
        $p=$request->post();
        $token = '';
        (isset($g['token']) && !empty($g['token'])) and ($token = $g['token']);
        (isset($p['token']) && !empty($p['token'])) and ($token = $p['token']);
        if(empty($token)){
            js_code('
                    var str = localStorage.getItem("token");
                    if(str !=="" || str.length>0){
                        var preg = /(\?token=.*|\?.*)/i
                        var href = location.href.replace(preg,"");
                        location.href=(href+"?token="+localStorage.getItem("token")).replace(/[?]{2,}/g,"?");
                    }else{
                        location.href="/admin_login_out";
                    }   
           ');
        }
        $jwt = new \app\common\controller\publics\Jwt();
        if(!($this->token = $jwt->is_token($token)) || empty(cookie('fwf_admin_name'))){
            $this->error('信息验证错误，请重新登录','/admin_login_out');
        }
    }


    //栏目列表
    public function category_list(){
        //检查权限
        power_check();
        //获取菜单
        $mca=['m'=>\think\facade\Request::module(),'c'=>\think\facade\Request::controller(),'a'=>\think\facade\Request::action()];
        $mca['mca'] = $mca['m'].'/'.$mca['c'].'/'.$mca['a'];
        $mca['ca'] = $mca['c'].'/'.$mca['a'];
        $new_menu = Cache::tag('menu')->get('menu');
        $this->assign('new_menu',$new_menu);
        $this->assign('mca',$mca);

        $this->assign('title',lang('category_list'));
        $category_list = Db::name('category')->order(['cate_order'=>'desc'])->select();
        $model_list = Db::name('model')->select();
        foreach ($model_list as $key => $value) {
            $arr[$value['model_id']] = $value;
        }
        $model_list = $arr; unset($arr);



        $this->assign('category_list',$category_list);
        $this->assign('model_list',$model_list);
        return $this->fetch();
    }
    //添加，修改栏目
    public function category_edit(Request $request){
        //检查权限
        power_check();
        //获取菜单
        $mca=['m'=>\think\facade\Request::module(),'c'=>\think\facade\Request::controller(),'a'=>\think\facade\Request::action()];
        $mca['mca'] = $mca['m'].'/'.$mca['c'].'/'.$mca['a'];
        $mca['ca'] = $mca['c'].'/'.$mca['a'];
        $new_menu = Cache::tag('menu')->get('menu');
        $this->assign('new_menu',$new_menu);
        $this->assign('mca',$mca);

        $id = $request->param('id');
        $t = lang('category_add');
        if($id){
            $t = lang('category_edit');
        }
        $this->assign('title',$t);

        $model_list = Db::name('model')->select();
        $category = Db::name('category')->where('cate_id','=',$id)->find();


        $this->assign('model_list',$model_list);
        $this->assign('category',$category);
        return $this->fetch();
    }
    //保存栏目
    public function category_save(Request $request){
        //检查权限
        power_check();

        $p = $request->post();
        $admin_id = cookie('fwf_admin_id');
        $id = $p['cate_id'];
        $validate = new \app\admin\validate\Content();
        if(!$validate->scene('category_save')->check($p)){
            $err = $validate->getError();
            $this->error(array_shift($err));
        }else{
            $data = [
                'cate_type'     => $p['cate_type'],
                'cate_name'     => $p['cate_name'],
                'cate_order'    => $p['cate_order'],
            ];
            if($id){
                //修改
                $up_n = Db::name('category')->where('cate_id','=',$id)->data($data)->update();
                if($up_n){
                    fwf_log('修改栏目信息，修改的ID：'.$id.'，操作管理员id：'.$admin_id.'，影响的行数：'.$up_n);
                }
                $this->success(lang('edit_success'),'/Content/category_edit/id/'.$id.'/?token='.$p['token']);
            }else{
                //添加
                $data['cate_admin_id'] = $admin_id;
                $insert_id = Db::name('category')->insertGetId($data);
                if ($insert_id){
                    fwf_log('添加栏目信息，添加的ID：'.$insert_id.'，操作管理员id：'.$admin_id);
                    $this->success(lang('add_success'),'/Content/category_list/?token='.$p['token']);
                }
                $this->error(lang('add_fail'),'/Content/category_list/?token='.$p['token']);
            }
        }

    }
    //删除栏目
    public function category_del(Request $request){
        //检查权限
        power_check();
        $id = $request->param('id');
        if($id){
            $del_n = Db::name('category')->where('cate_id','=',$id)->delete();
            if($del_n){
                fwf_log('删除栏目，删除的ID：'.$id.'，操作管理员id：'.cookie('fwf_admin_id').'，删除的行数：'.$del_n);
                $this->redirect('/Content/category_list/');
            }
        }
        $this->error(lang('del_fail'));

    }
    //异步修改栏目
    public function category_edit_ajax(Request $request){
        //检查权限
        $ok=power_check(1);
        $g = $request->get();
        $admin_id = cookie('fwf_admin_id');
        if($ok){
            if($g['id']!='' && $g['f'] && $g['v']){
                $up_n = Db::name('catagory')->where('cate_id','=',$g['id'])->data([ $g['f'] => $g['v'] ])->update();
                if($up_n){
                    fwf_log('异步修改栏目信息，修改的ID：'.$g['id'].'，修改的字段：'.$g['f'].'，操作管理员ID：'.$admin_id);
                    return_json(1,1,lang('edit_success'));
                }
            }
        }
        return_json(0,2,lang('edit_fail'));
    }



    //文章列表
    public function article_list(Request $request){
        //检查权限
        power_check();
        //获取菜单
        $mca=['m'=>\think\facade\Request::module(),'c'=>\think\facade\Request::controller(),'a'=>\think\facade\Request::action()];
        $mca['mca'] = $mca['m'].'/'.$mca['c'].'/'.$mca['a'];
        $mca['ca'] = $mca['c'].'/'.$mca['a'];
        $new_menu = Cache::tag('menu')->get('menu');
        $this->assign('new_menu',$new_menu);
        $this->assign('mca',$mca);

        $this->assign('title',lang('article_list'));

        $admin_id = cookie('fwf_admin_id');
        /*******分页部分 start */
        $g = $request->get();
        $param = $request->param();
        /*($param['page_rows']) or ($param['page_rows'] = 15);
        ($param['page']) or ($param['page'] = 1);
        //当前页数
        $g['page'] = $page = intval($param['page']);
        //每页的行数
        $g['page_rows'] = $rows = intval($param['page_rows']);*/
        //总行数
        $g['rowCount'] = $rowCount = Db::table('fwf_media')->where('media_member_id','in',[$admin_id])->count();
        paging($rowCount,$param,$g);
        $this->assign('get',$g);
        /*******分页部分 end  */

        $article_list = Db::table('fwf_media')->alias('m')
            //->field('m.*,a.member_user,a.is_admin')
            ->field('m.media_id,m.media_title,m.meida_add_time,a.member_user,a.is_admin')
            ->leftJoin('fwf_member a','m.media_member_id = a.member_id')
            ->where('m.media_member_id','=',$admin_id)
            ->order(['m.media_id'=>'desc'])
            ->limit(($page-1)*$rows,$rows)
            ->select();



        $this->assign('article_list',$article_list);
        return $this->fetch();

    }
    //添加，修改文章
    public function article_edit(Request $request){
        //检查权限
        power_check();
        //获取菜单
        $mca=['m'=>\think\facade\Request::module(),'c'=>\think\facade\Request::controller(),'a'=>\think\facade\Request::action()];
        $mca['mca'] = $mca['m'].'/'.$mca['c'].'/'.$mca['a'];
        $mca['ca'] = $mca['c'].'/'.$mca['a'];
        $new_menu = Cache::tag('menu')->get('menu');
        $this->assign('new_menu',$new_menu);
        $this->assign('mca',$mca);

        $id = $request->param('id');
        $t = lang('article_add');
        if($id){
            $t = lang('article_edit');
        }
        $this->assign('title',$t);
        //开启KindEditor 并设置相关选项
        $this->assign('KE',1);
        $this->assign('KEs',['del'=>1]);
        //获取文章内容
        $article = Db::table('fwf_media')->alias('a')->field('a.*,c.cate_type,c.cate_name')
            ->leftJoin('fwf_category c','a.media_category_id = c.cate_id')
            ->where('a.media_id','=',$id)->find();
        if(!$article){
            $article=[];
        }
        //获取模型信息
        $model_list = Db::name('model')->field('model_id,model_fields')->where('model_action',['=',$mca['ca']],['=',$mca['c']],'or')->select();
        foreach ($model_list as $item) {
            $model_ids[] = $item['model_id'];
            if($article['cate_type'] == $item['model_id']){
                //获取所需字段信息
                $model_fields = unserialize($item['model_fields']);
            }else{
                $model_fields = unserialize($model_list[0]['model_fields']);
            }
        }
        //获取栏目信息，根据获取到的模型
        $category_lsit = Db::name('category')->where('cate_type','in',$model_ids)->select();



        $this->assign('category_list',$category_lsit);
        $this->assign('model_fields',$model_fields);
        $this->assign('data',$article);
        $this->assign('article',$article);
        return $this->fetch();

    }
    //保存文章
    public function article_save(Request $request){
        //检查权限
        power_check();

        $p = $request->post();
        $admin_id = cookie('fwf_admin_id');
        $id = $p['media_id'];
        $validate = new \app\admin\validate\Content();
        if(!$validate->article_save($p)){
            $err = $validate->getError();
            $this->error(array_shift($err));
        }else{
            $data = [
                'media_title'           => $p['media_title'],
                'media_category_id'     => $p['media_category_id'],
                'meida_img'             => $p['meida_img'],
                'media_desc'            => $p['media_desc'],
                'media_content'         => $p['media_content'],
            ];
            if($id){
                //修改
                $up_n = Db::name('media')->where('media_id','=',$id)->data($data)->update();
                if($up_n){
                    fwf_log('修改文章信息，修改的ID：'.$id.'，操作管理员id：'.$admin_id.'，影响的行数：'.$up_n);
                }
                $this->success(lang('edit_success'),'/Content/article_edit/id/'.$id.'/?token='.$p['token']);
            }else{
                //添加
                $data['media_member_id'] = $admin_id;
                $insert_id = Db::name('media')->insertGetId($data);
                if ($insert_id){
                    fwf_log('添加文章信息，添加的ID：'.$insert_id.'，操作管理员id：'.$admin_id);
                    $this->success(lang('add_success'),'/Content/article_list/?token='.$p['token']);
                }
                $this->error(lang('add_fail'),'/Content/article_list/?token='.$p['token']);
            }
        }


    }
    //删除文章
    public function article_del(Request $request){
        //检查权限
        power_check();
        $id = $request->param('id');
        if($id){
            $del_n = Db::name('media')->where('media_id','=',$id)->delete();
            if($del_n){
                fwf_log('删除文章，删除的ID：'.$id.'，操作管理员id：'.cookie('fwf_admin_id').'，删除的行数：'.$del_n);
                $this->redirect('/Content/article_list/');
            }
        }
        $this->error(lang('del_fail'));

    }
    //异步修改文章部分内容
    public function article_edit_ajax(Request $request){
        //检查权限
        $ok=power_check(1);
        $g = $request->get();
        $admin_id = cookie('fwf_admin_id');
        if($ok){
            if($g['id']!='' && $g['f'] && $g['v']){
                $up_n = Db::name('media')->where('media_id','=',$g['id'])->data([ $g['f'] => $g['v'] ])->update();
                if($up_n){
                    fwf_log('异步修改文章，修改的ID：'.$g['id'].'，修改的字段：'.$g['f'].'，操作管理员ID：'.$admin_id);
                    return_json(1,1,lang('edit_success'));
                }
            }
        }
        return_json(0,2,lang('edit_fail'));

    }


    //前台配置列表
    public function config_list(){
        //检查权限
        power_check();
        //获取菜单
        $mca=['m'=>\think\facade\Request::module(),'c'=>\think\facade\Request::controller(),'a'=>\think\facade\Request::action()];
        $mca['mca'] = $mca['m'].'/'.$mca['c'].'/'.$mca['a'];
        $mca['ca'] = $mca['c'].'/'.$mca['a'];
        $new_menu = Cache::tag('menu')->get('menu');
        $this->assign('new_menu',$new_menu);
        $this->assign('mca',$mca);

        $this->assign('title',lang('config_list'));
        $admin_id = cookie('fwf_admin_id');

        $GLOBALS['tree']['pid'] = 'config_pid';
        $GLOBALS['tree']['id'] = 'config_id';
        $config_list = Db::table('fwf_config')->order(['config_order'=>'desc'])->select();
        $config_list = get_leval_list(1,2,$config_list);


        $this->assign('config_list',$config_list);
        return $this->fetch();
    }
    //添加，修改前台配置
    public function config_edit(Request $request){
        //检查权限
        power_check();
        //获取菜单
        $mca=['m'=>\think\facade\Request::module(),'c'=>\think\facade\Request::controller(),'a'=>\think\facade\Request::action()];
        $mca['mca'] = $mca['m'].'/'.$mca['c'].'/'.$mca['a'];
        $mca['ca'] = $mca['c'].'/'.$mca['a'];
        $new_menu = Cache::tag('menu')->get('menu');
        $this->assign('new_menu',$new_menu);
        $this->assign('mca',$mca);

        $id = $request->param('id');
        $t = lang('config_add');
        if($id){
            $t = lang('config_edit');
        }
        $this->assign('title',$t);

        $admin_id = cookie('fwf_admin_id');
        $config = Db::name('config')->where('config_id','=',$id)->find();
        $config_pid_list = Db::name('config')->select();
        $GLOBALS['tree']['pid'] = 'config_pid';
        $GLOBALS['tree']['id'] = 'config_id';
        $config_pid_list = get_leval_list($id,2,$config_pid_list);
        $config_img_list = explode(',',$config['config_img']);
        if(count($config_img_list)==1 && in_array($config_img_list[0],['',','])){
            $config_img_list = [];
        }


        //开启KindEditor 并设置相关选项
        $this->assign('KE',1);
        $this->assign('KEs',['del'=>1]);


        $this->assign('config',$config);
        $this->assign('config_pid_list',$config_pid_list);
        $this->assign('config_img_list',$config_img_list);
        return $this->fetch();
    }
    //保存前台配置
    public function config_save(Request $request){
        //检查权限
        power_check();

        $p = $request->post();
        $admin_id = cookie('fwf_admin_id');
        $id = $p['config_id'];
        $validate = new \app\admin\validate\Content();
        if(!$validate->scene('config_save')->check($p)){
            $err = $validate->getError();
            $this->error(array_shift($err));
        }else{
            $config_img = '';
            if(isset($p['meida_imgs']) && is_array($p['meida_imgs']) ){
                $config_img = join(',',$p['meida_imgs']);
            }

            $data = [
                'config_pid'            => $p['config_pid'],
                'config_name'           => $p['config_name'],
                'config_url'            => $p['config_url'],
                'config_order'          => $p['config_order'],
                'config_desc'           => $p['config_desc'],
                'config_img'            => $config_img,
                'config_extend'         => $p['config_extend'],
                'config_status'         => $p['config_status'],
            ];
            if($id){
                //修改
                $up_n = Db::name('config')->where('config_id','=',$id)->data($data)->update();
                if($up_n){
                    fwf_log('修改前台配置信息，修改的ID：'.$id.'，操作管理员id：'.$admin_id.'，影响的行数：'.$up_n);
                }
                $this->success(lang('edit_success'),'/Content/config_edit/id/'.$id.'/?token='.$p['token']);
            }else{
                //添加
                $insert_id = Db::name('config')->insertGetId($data);
                if ($insert_id){
                    fwf_log('添加前台配置信息，添加的ID：'.$insert_id.'，操作管理员id：'.$admin_id);
                    $this->success(lang('add_success'),'/Content/config_list/?token='.$p['token']);
                }
                $this->error(lang('add_fail'),'/Content/config_list/?token='.$p['token']);
            }
        }
    }
    //删除配置
    public function config_del(Request $request){
        //检查权限
        power_check();
        $id = $request->param('id');
        if($id){
            $del_n = Db::name('config')->where('config_id','=',$id)->delete();
            if($del_n){
                fwf_log('删除前台配置，删除的ID：'.$id.'，操作管理员id：'.cookie('fwf_admin_id').'，删除的行数：'.$del_n);
                $this->redirect('/Content/config_list/');
            }
        }
        $this->error(lang('del_fail'));
    }
    //异步修改前台配置信息
    public function config_edit_ajax(Request $request){
        //检查权限
        $ok=power_check(1);
        $g = $request->get();
        $admin_id = cookie('fwf_admin_id');
        if($ok){
            if($g['id']!='' && $g['f'] && $g['v']){
                $up_n = Db::name('config')->where('config_id','=',$g['id'])->data([ $g['f'] => $g['v'] ])->update();
                if($up_n){
                    fwf_log('异步修改前台配置，修改的ID：'.$g['id'].'，修改的字段：'.$g['f'].'，操作管理员ID：'.$admin_id);
                    return_json(1,1,lang('edit_success'));
                }
            }
        }
        return_json(0,2,lang('edit_fail'));
    }

}
